
import 'package:banyou_app/app/config/colors.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';


class MultiRowInput extends StatefulWidget {
  final String hint;
  final double height;
  final int? maxLength;
  final TextEditingController textEditingController;
  final Function(String) onChanged;

  MultiRowInput(
    this.hint,
    this.onChanged,
    this.height,
    this.textEditingController, {
    this.maxLength = 250,
  });

  @override
  State<MultiRowInput> createState() => MultiRowInputState();
}

class MultiRowInputState extends State<MultiRowInput> {
  // String result = "";
  // late TextEditingController controller;
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: _textInput(widget.hint),
    );
  }

  _textInput(String hint) {
    return Stack(
      alignment: AlignmentDirectional.bottomEnd,
      children: [
        Container(
          height: widget.height,
          decoration: BoxDecoration(
            color: ColorConfig.white,
            borderRadius: BorderRadius.all(
              Radius.circular(4.0),
            ),
            // border: Border.all(color: Color(0xFFDEDEDE)),
          ),
          alignment: AlignmentDirectional.topStart,
          margin: EdgeInsets.only(bottom: 20),
          child: CupertinoTextField(
            controller: widget.textEditingController,
            keyboardAppearance: Brightness.light,
            placeholder: hint,
            style: TextStyle(
                fontSize: 15,
                textBaseline: TextBaseline.alphabetic,
                color: ColorConfig.body1_txt_color),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(2)),
            ),
            maxLines: 10,
            maxLength: widget.maxLength,
            inputFormatters: widget.maxLength != null
                ? [
                    // 只能输入汉字或者字母或数字
                    // CustomizedTextInputFormatter(
                    //   RegExp("[a-zA-Z]|[\u4e00-\u9fa5]|[0-9]"),
                    // ),
                    MTLengthLimitingTextInputFormatter(
                        widget.maxLength ?? 0, () {})
                    // LengthLimitingTextInputFormatter(widget.maxLength)
                  ]
                : null,
            maxLengthEnforcement: MaxLengthEnforcement.none,
            textInputAction: TextInputAction.unspecified,
            onChanged: (str) {
              widget.onChanged(widget.textEditingController.text);
              setState(() {});
            },
          ),
        ),
        widget.maxLength != null
            ? Container(
                margin: EdgeInsets.only(bottom: 10, right: 20),
                child: Text(
                  widget.textEditingController.text.length.toString() +
                      "/${widget.maxLength}",
                  style: TextStyle(color: ColorConfig.text_label, fontSize: 14),
                ),
              )
            : Container()
      ],
    );
  }
}

class MTLengthLimitingTextInputFormatter extends TextInputFormatter {
  MTLengthLimitingTextInputFormatter(this.maxLength, this.maxLengthCallBack)
      : assert(maxLength == null || maxLength == -1 || maxLength > 0);

  final int maxLength;

  bool hasAlreadyMaxLength = false;

  ///超过文本长度回调
  final Function maxLengthCallBack;

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue, // unused.
    TextEditingValue newValue,
  ) {
    hasAlreadyMaxLength = oldValue.text.length >= maxLength;
    if (!hasAlreadyMaxLength &&
        maxLength != null &&
        maxLength > 0 &&
        newValue.text.length >= maxLength) {
      ///第一次超长
      if (maxLengthCallBack != null) maxLengthCallBack();
      return _resetSelection(newValue);
    } else if (hasAlreadyMaxLength &&
        maxLength != null &&
        maxLength > 0 &&
        newValue.text.length >= maxLength) {
      ///第二次往后超长
      if (maxLengthCallBack != null) maxLengthCallBack();
      return _initOldDataSelection(oldValue, newValue);
    } else {
      hasAlreadyMaxLength = false;
      return newValue;
    }
  }

  TextEditingValue _resetSelection(TextEditingValue newValue) {
    hasAlreadyMaxLength = true;
    var sRunes = newValue.text.runes;
    String result = '';
    int i = 0;
    for (i = 0; i < sRunes.length; i++) {
      if (String.fromCharCodes(sRunes, 0, sRunes.length - i).length <=
          maxLength) {
        result = String.fromCharCodes(sRunes, 0, sRunes.length - i);
        if (result.runes.last == 105) {
          //如果删除后剩下的还有一个空格，继续删除
          result =
              String.fromCharCodes(result.runes, 0, result.runes.length - 1);
        }
        break;
      }
    }
    TextSelection temp = newValue.selection.copyWith(
      baseOffset: result.length,
      extentOffset: result.length,
    );
    TextRange fixRange = newValue.composing;
    if (newValue.composing.end > result.length) {
      fixRange = TextRange(start: fixRange.start - i, end: result.length);
    }
    return TextEditingValue(text: result, selection: temp, composing: fixRange);
  }

  TextEditingValue _initOldDataSelection(
      TextEditingValue oldValue, TextEditingValue newValue) {
    TextSelection actualSelection = newValue.selection;
    actualSelection = newValue.selection.copyWith(
      baseOffset: oldValue.text.length,
      extentOffset: oldValue.text.length,
    );
    //ios:当TextRange不为-1时候，下次update会把start和end直接的变量值全部丢弃。当你确定内容不变时候，请把他们变成-1
    TextRange fixRange = TextRange(start: -1, end: -1);
    return TextEditingValue(
        text: oldValue.text, selection: actualSelection, composing: fixRange);
  }
}

/// 自定义兼容中文拼音输入法正则校验输入框
class CustomizedTextInputFormatter extends TextInputFormatter {
  final Pattern filterPattern;

  CustomizedTextInputFormatter(this.filterPattern);

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    if (newValue.isComposingRangeValid) return newValue;
    return FilteringTextInputFormatter.allow(filterPattern)
        .formatEditUpdate(oldValue, newValue);
  }
}

/// 自定义兼容中文拼音输入法长度限制输入框
class CustomizedLengthTextInputFormatter extends TextInputFormatter {
  final int maxLength;

  CustomizedLengthTextInputFormatter(this.maxLength);

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    if (newValue.isComposingRangeValid) return newValue;
    return LengthLimitingTextInputFormatter(maxLength)
        .formatEditUpdate(oldValue, newValue);
  }
}
